/**
 * @file lv_port_disp_templ.c
 *
 */

/*Copy this file as "lv_port_disp.c" and set this value to "1" to enable content*/
#if 1

/*********************
 *      INCLUDES
 *********************/
#include <stdbool.h>
#include <stdio.h>
#include "lv_port_display.h"
#include "sdl_render.h"
#ifdef LV_LVGL_H_INCLUDE_SIMPLE
#include "lvgl.h"
#else
#include "lvgl/lvgl.h"
#endif

/*********************
 *      DEFINES
 *********************/
#ifndef MY_DISP_HOR_RES
    #warning Please define or replace the macro MY_DISP_HOR_RES with the actual screen width, default value 320 is used for now.
    #define MY_DISP_HOR_RES    320
#endif

#ifndef MY_DISP_VER_RES
    #warning Please define or replace the macro MY_DISP_VER_RES with the actual screen height, default value 240 is used for now.
    #define MY_DISP_VER_RES    240
#endif

#if (LV_COLOR_DEPTH == 8)
#define COLOR_TYPE uint8_t
#elif (LV_COLOR_DEPTH == 16)
#define COLOR_TYPE lv_color_t
#elif (LV_COLOR_DEPTH == 24)
#define COLOR_TYPE lv_color16_t
#elif (LV_COLOR_DEPTH == 32)
#define COLOR_TYPE lv_color32_t
#else
#error error LV_COLOR_DEPTH value
#endif

#define BUFFER_EXAMPLE      3

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/
static void disp_init(void);

static void disp_flush(lv_display_t * disp, const lv_area_t * area, uint8_t * px_map);

static void disp_refresh(const SDL_Event *, void *, void *);

/**********************
 *  STATIC VARIABLES
 **********************/

static volatile bool disp_flush_enabled = true;

static sdl_event_handle_t events[] = {
    { .type = SDL_WINDOWEVENT, .fn = disp_refresh, .arg = NULL },
};
static sdl_event_handle_arr_t eventsInfo = {
    .arr = events,
    .arrlen = sizeof(events) / sizeof(events[0])
};

/**********************
 *      MACROS
 **********************/
#ifdef DEBUG
#define LOG(fmt, ...)   fprintf(stderr, "[%s:%s(%u)] " fmt "\n", \
        __FILE__, __func__, __LINE__, ##__VA_ARGS__)
#else
#define LOG(fmt, ...)
#endif

/**********************
 *   GLOBAL FUNCTIONS
 **********************/

void lv_port_disp_init(void)
{
    /*-------------------------
     * Initialize your display
     * -----------------------*/

    /*------------------------------------
     * Create a display and set a flush_cb
     * -----------------------------------*/
    lv_display_t * disp = lv_display_create(MY_DISP_HOR_RES, MY_DISP_VER_RES);
    if (disp == NULL)   return;
    lv_display_set_flush_cb(disp, disp_flush);

    void * handle = sdl_window_create("LVGL", MY_DISP_HOR_RES, MY_DISP_VER_RES);
    if (handle == NULL) return;
    eventsInfo.lvglDrv = disp;
    sdl_event_listen(handle, &eventsInfo);
    lv_display_set_driver_data(disp, handle);

#if BUFFER_EXAMPLE == 1
    /* Example 1
     * One buffer for partial rendering*/
    static COLOR_TYPE buf_1_1[MY_DISP_HOR_RES * MY_DISP_VER_RES / 10];  /*A buffer for 1/10 rows*/
    lv_display_set_buffers(disp, buf_1_1, NULL, sizeof(buf_1_1), LV_DISPLAY_RENDER_MODE_PARTIAL);

#elif BUFFER_EXAMPLE == 2
    /* Example 2
     * Two buffers for partial rendering
     * In flush_cb DMA or similar hardware should be used to update the display in the background.*/
    static COLOR_TYPE buf_2_1[MY_DISP_HOR_RES * 10];
    static COLOR_TYPE buf_2_2[MY_DISP_HOR_RES * 10];
    lv_display_set_buffers(disp, buf_2_1, buf_2_2, sizeof(buf_2_1), LV_DISPLAY_RENDER_MODE_PARTIAL);

#elif BUFFER_EXAMPLE == 3
    /* Example 3
     * Two buffers screen sized buffer for double buffering.
     * Both LV_DISPLAY_RENDER_MODE_DIRECT and LV_DISPLAY_RENDER_MODE_FULL works, see their comments*/
    static COLOR_TYPE buf_3_1[MY_DISP_HOR_RES * MY_DISP_VER_RES];
    static COLOR_TYPE buf_3_2[MY_DISP_HOR_RES * MY_DISP_VER_RES];
//    lv_display_set_buffers(disp, buf_3_1, buf_3_2, sizeof(buf_3_1), LV_DISPLAY_RENDER_MODE_DIRECT);
//    lv_display_set_buffers(disp, buf_3_1, buf_3_2, sizeof(buf_3_1), LV_DISPLAY_RENDER_MODE_FULL);
    lv_display_set_buffers(disp, buf_3_1, buf_3_2, sizeof(buf_3_1), LV_DISPLAY_RENDER_MODE_PARTIAL);
#endif
}


/**********************
 *   STATIC FUNCTIONS
 **********************/

static void disp_refresh(const SDL_Event * e, void * lvglDrv, void * arg)
{
    (void) lvglDrv;
    (void) arg;
    if (e->type != SDL_WINDOWEVENT)  return;

    if (lvglDrv == NULL)    return;
    lv_display_t * disp = lvglDrv;

    switch (e->window.event)
    {
    case SDL_WINDOWEVENT_RESTORED:
        lv_obj_invalidate(lv_display_get_screen_active(disp));
        lv_refr_now(disp);
        break;
    }
}

/*Initialize your display and the required peripherals.*/
static void disp_init(void)
{
    /*You code here*/
}


/* Enable updating the screen (the flushing process) when disp_flush() is called by LVGL
 */
void disp_enable_update(void)
{
LOG("\nEnable display update.\n");
    disp_flush_enabled = true;
}

/* Disable updating the screen (the flushing process) when disp_flush() is called by LVGL
 */
void disp_disable_update(void)
{
LOG("\nDisable display update.\n");
    disp_flush_enabled = false;
}


static void disp_draw_px_a8(void * handle, uint32_t x, uint32_t y, void ** ppx)
{
    uint8_t * px = (*ppx)++;
    sdl_draw_point(handle, x, y, *px, *px, *px, 255);
}

static void disp_draw_px_rgb565(void * handle, uint32_t x, uint32_t y, void ** ppx)
{
    union {
        uint16_t        pxVal;
        lv_color16_t    field;
    } px;

    px.pxVal = *(uint16_t *)*ppx;
    sdl_draw_point(handle, x, y, px.field.red << 3, px.field.green << 2, px.field.blue << 3, 255);

    (*ppx) += 2;
}

static void disp_draw_px_rgb888(void * handle, uint32_t x, uint32_t y, void ** ppx)
{
    uint8_t * p = (uint8_t *) (*ppx);
    lv_color_t px;
    px.blue = *p++;
    px.green = *p++;
    px.red = *p++;
    sdl_draw_point(handle, x, y, px.red, px.green, px.blue, 255);

    (*ppx) = p;
}

static void disp_draw_px_xrgb8888(void * handle, uint32_t x, uint32_t y, void ** ppx)
{
    union {
        uint32_t        pxVal;
        lv_color32_t    field;
    } px;

    px.pxVal = *(uint32_t *)(*ppx);
    sdl_draw_point(handle, x, y, px.field.red, px.field.green, px.field.blue, px.field.alpha);

    (*ppx) += 4;
}

/*Flush the content of the internal buffer the specific area on the display.
 *`px_map` contains the rendered image as raw pixel map and it should be copied to `area` on the display.
 *You can use DMA or any hardware acceleration to do this operation in the background but
 *'lv_display_flush_ready()' has to be called when it's finished.*/
static void disp_flush(lv_display_t * disp_drv, const lv_area_t * area, uint8_t * px_map)
{
    if (disp_flush_enabled) {
        void * handle = lv_display_get_driver_data(disp_drv);

LOG("(%d, %d) - (%d, %d)", area->x1, area->y1, area->x2, area->y2);

        /*The most simple case (but also the slowest) to put all pixels to the screen one-by-one*/

        int32_t x;
        int32_t y;
        for(y = area->y1; y <= area->y2; y++) {
            for(x = area->x1; x <= area->x2; x++) {

                /*Put a pixel to the display. For example:*/
                /*put_px(x, y, *px_map)*/
#if (LV_COLOR_DEPTH == 8)
                disp_draw_px_a8(handle, x, y, (void **) &px_map);
#elif (LV_COLOR_DEPTH == 16)
                disp_draw_px_rgb565(handle, x, y, (void **) &px_map);
#elif (LV_COLOR_DEPTH == 24)
                disp_draw_px_rgb888(handle, x, y, (void **) &px_map);
#elif (LV_COLOR_DEPTH == 32)
                disp_draw_px_xrgb8888(handle, x, y, (void **) &px_map);
#endif
            }
        }

        sdl_update_screen(handle);
    }


    /*IMPORTANT!!!
     *Inform the graphics library that you are ready with the flushing*/
    lv_display_flush_ready(disp_drv);
}

#else /*Enable this file at the top*/

/*This dummy typedef exists purely to silence -Wpedantic.*/
typedef int keep_pedantic_happy;
#endif
